package com.sc.javaee.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.javaee.pojo.Result;
import com.sc.javaee.util.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        //获取前端请求头传递过来的token信息
        String token=request.getHeader("token");
        System.out.println("token信息:"+token);
        if (JwtUtils.checkToken(token)){//合法的token
            return true;
        }
        PrintWriter pw=response.getWriter();
        //可以将java中对象转换成json对象
        //new ObjectMapper().writeValueAsString(对象)
        pw.write(new ObjectMapper()
                .writeValueAsString(new Result(0,"认证失败")));
        return false;
    }
}
